import { getTokenKey } from "../../utils/auth"

var QQMapWX = require('../../qqmap/qqmap-wx-jssdk.min');
var qqmapsdk = new QQMapWX({key: 'FBJBZ-2ZLC3-W4U3L-36L33-K5II7-QSBO7'});
const app = getApp();

// 标记的 id
var markerId = 1;

// 消防站标记点
var stationMarkers = []
// 消火栓标记点
var fireHydrantMarkers = [];
// 线段
var currentLines = [];
var lineMarkers = [];
// 区域标记点
var currentGons = [];
var gonMarkers = [];
// 圆圈标记点
var others = [];
var otherMarkers = [];
// 已加载的消火栓区域
var hydrantsLoadingArea = [];
// 已加载的线段区域
var linesLoadingArea = [];
// 已加载的区域标记
var gonsLoadingArea = [];
// 已加载其它标记
var othersLoadingArea = [];
// 目的地标记点
var descMarker=[];
// map上下文
var mapCtx;

const intact_hydrant_img = '../../images/hydrant.png';
const damage_hydrant_img = '../../images/damage_hydrant.png';

Component({
  properties: {
    current_loc_latitude: {
      type:String,
      default:''
    },
    current_loc_longitude: {
      type:String,
      default:''
    },
    current_loc_title: {
      type:String,
      default:''
    },
    markerClassId: {
      type:Number,
      default : 0
    }
  },
  data: {
    // 上一个展示区域
    lastRegion:{
      northeast:'',
      southwest:''
    },
    //当前展示区域
    currentRegion:{
      northeast:'',
      southwest:''
    },
    //搜索目的地
    destination:{
      latitude:'',
      longitude:'',
      title:'',
      address:''
    },
    scale:16,
    isShowExistMarkers:false,
    polyLines: [],
    polyGons:[],
    circles:[],
    province:'',
    city:''
  },
  lifetimes: {
    //执行一次
    attached: function() {
      this._initMapCtx()
    },

  },
  methods: {
    //初始化地图组件
    _initMapCtx:function(){
      mapCtx = wx.createMapContext('myMap',this)
      var that = this
      // 保存当前region
      mapCtx.getRegion({
        complete(res){
          that.setData({
            'lastRegion.northeast':res.northeast,
            'lastRegion.southwest':res.southwest,
            'currentRegion.northeast':res.northeast,
            'currentRegion.southwest':res.southwest,
          }) 
        }
      })
      this._loadStation()
      this.bindEvent()
    },

    clearData(){
      fireHydrantMarkers = [];
      currentLines = [];
      lineMarkers = [];
      currentGons = [];
      gonMarkers = [];
      others = [];
      otherMarkers = [];
      hydrantsLoadingArea = [];
      linesLoadingArea = [];
      gonsLoadingArea = [];
      othersLoadingArea = [];
      this.setData({
        isShowExistMarkers:false,
        polyLines: [],
        polyGons:[],
        circles:[],
      })
    },

    bindEvent() {
      mapCtx.initMarkerCluster({
        enableDefaultStyle: true,
        zoomOnClick: true,
        gridSize:30,
        success(res){
          console.log('initMarkerCluster', res)
        }
      })
    },
    
    //视图变化
    ChangeRegion(e){
      if(e.type==='end'){
        const{ region } = e.detail
        const{ scale } = e.detail
        // 更新currentRegion
        this.setData({
          'currentRegion.northeast' : region.northeast,
          'currentRegion.southwest' : region.southwest
        })
        // 如果缩放大于13，
        if(scale > 13){
          //设置加载区域           
          if((region.northeast.latitude < this.data.lastRegion.northeast.latitude && region.northeast.longitude < this.data.lastRegion.northeast.longitude) && (region.southwest.latitude > this.data.lastRegion.southwest.latitude && region.southwest.longitude > this.data.lastRegion.southwest.longitude)){
            //放大操作，不进行设施显示区域变换  
            console.log("放大操作")
            this.showMarkers()
            this.setData({
              'lastRegion.northeast':region.northeast,
              'lastRegion.southwest':region.southwest,
            })
          }else if((region.northeast.latitude > (this.data.lastRegion.northeast.latitude + 0.001) && region.northeast.longitude > (this.data.lastRegion.northeast.longitude + 0.001))&& (region.southwest.latitude < (this.data.lastRegion.southwest.latitude - 0.001) && region.southwest.longitude < (this.data.lastRegion.southwest.longitude - 0.001))){
            //获取未加载区域 1()latitude纵坐标 longitude 横坐标  但考虑到频繁请求数据库  当缩小为100米以上时，重新设置markers
            console.log("缩小操作")
            this.showMarkers()
            //更新lastRegion
            this.setData({
              'lastRegion.northeast':region.northeast,
              'lastRegion.southwest':region.southwest,
            })
          }else{
            if((region.southwest.longitude > this.data.lastRegion.northeast.longitude)||(region.northeast.longitude < this.data.lastRegion.southwest.longitude)||(region.southwest.latitude >  this.data.lastRegion.northeast.latitude) || (region.northeast.latitude < this.data.lastRegion.southwest.latitude)){
              console.log("完全移动操作")
              this.showMarkers()
              this.setData({
                'lastRegion.northeast':region.northeast,
                'lastRegion.southwest':region.southwest,
              })

            }else if(((this.data.lastRegion.southwest.longitude +  0.0001) < region.southwest.longitude < this.data.lastRegion.northeast.longitude) || ((this.data.lastRegion.southwest.latitude +  0.0001) < region.southwest.latitude < this.data.lastRegion.northeast.latitude) || ( this.data.lastRegion.southwest.longitude < region.northeast.longitude < (this.data.lastRegion.northeast.longitude - 0.0001)) ||( this.data.lastRegion.southwest.latitude < region.northeast.latitude < (this.data.lastRegion.northeast.latitude -0.0001 ))){
              console.log("非完全移动操作")
              //需增大 lastRegion面积
              this.showMarkers()
              this.setData({
                'lastRegion.northeast':region.northeast,
                'lastRegion.southwest':region.southwest,
              })
            }else{
              console.log('移动较小',this.data.lastRegion)
              if(this.data.lastRegion.northeast!==''){  
                //this.data.lastRegion
                this.showMarkers()
              }
            }
          }  
        }else{
          //隐藏marker
          console.log('调用removeMarker')
          this.removeMarkers()
        } 
     }
    },
    // 展示标记
    showMarkers(){
      // 先以区域为单位进行大面积核对
      const {...currentRegion} = this.data.currentRegion
      switch(this.data.markerClassId){
          case 0:
            console.log(0)
            break;
          case 1:  
            // 未展示时显示现有marker
            if(!this.data.isShowExistMarkers){
              this.addMarkers(fireHydrantMarkers)
            }
            // 先以区域为单位进行大面积核对
            let isUnloading= this.checkArea(hydrantsLoadingArea, currentRegion)
            if(isUnloading){
              console.log('加载区域')
              this.showHydrantMarkers(currentRegion)    
            }
            break;
          case 2:
            if(!this.data.isShowExistMarkers){
              this.addCurrentLines()
            }
             let isLineUnloading= this.checkArea(linesLoadingArea, currentRegion)
             if(isLineUnloading){
               this.showLines(currentRegion) 
             }
            break;
          case 3:
            if(!this.data.isShowExistMarkers){
              this.addCurrentGons()
            }
            let isGonUnloading= this.checkArea(gonsLoadingArea, currentRegion)
            if(isGonUnloading){
              this.showGons(currentRegion) 
            }
            break;
          case 4:
            if(!this.data.isShowExistMarkers){
              this.addOthers()
            }
            let isOthersUnloading= this.checkArea(othersLoadingArea, currentRegion)
            if(isOthersUnloading){
              this.showOthers(currentRegion)
            }
            break; 
      }
    },

    //核对区域是否未加载
    checkArea(loadingArea, currentRegion){
      //核对currentRegion，看是否已经加载
      let isUnLoading = true
      //涉及到对象深拷贝
      var {...Area} = currentRegion
      if(currentRegion.northeast !== ''){
          if(loadingArea.length !== 0){
            isUnLoading = this._checkUnLoadingArea(loadingArea, currentRegion)
          }else{
            loadingArea.push(Area)
        }
      }else{
        isUnLoading = false
      }
      return isUnLoading
    },
   
    //核对区域是否未加载
    _checkUnLoadingArea(loadingArea, currentRegion){
      var isUnloading = true
        //！！！在js中 3<2<5是正确
      let len = loadingArea.length;
      for(let i = 0; i < len; i++){
        let item = loadingArea[i]
        if(((item.southwest.longitude <= currentRegion.northeast.longitude)&& (currentRegion.northeast.longitude <= item.northeast.longitude)) && ((item.southwest.latitude <= currentRegion.northeast.latitude) && (currentRegion.northeast.latitude <= item.northeast.latitude)) && ((item.southwest.longitude <= currentRegion.southwest.longitude) && (currentRegion.southwest.longitude <= item.northeast.longitude)) && ((item.southwest.latitude <= currentRegion.southwest.latitude) &&  (currentRegion.southwest.latitude <= item.northeast.latitude))){
          isUnloading = false;
          break;
        }
      }
      if (isUnloading === true){
        //涉及到对象深拷贝
        loadingArea.push(currentRegion)
      }
      return isUnloading
    },
    // 展示当前区域水源标记
    async showHydrantMarkers(currentRegion){  
      const newMarkers = []
      const resp = await app.call({
        path:'/hydrant/search',
        method: 'post',
        data : {
          minLatitude : currentRegion.southwest.latitude,
          maxLatitude : currentRegion.northeast.latitude,
          minLongitude: currentRegion.southwest.longitude,
          maxLongitude: currentRegion.northeast.longitude,
          size: 600
        }
      })
      let iconPath = ''
      console.log(resp)
      if(resp.content){
        resp.content.forEach((item)=>{
          if(item.status === true){
            iconPath = intact_hydrant_img
          }else{
            iconPath = damage_hydrant_img
          }
          const newMarker = {
            id: markerId, //  前端标识
            itemId: item.id, // 服务器端生成的id 为String类型
            type: "hydrant",
            iconPath: iconPath,
            width: 30,
            height: 30,
            joinCluster: true, // 指定了该参数才会参与聚合
            latitude:item.latitude,
            longitude:item.longitude,
          } 
          //添加新fireHydrantMarkers中没有的marker
          let count = 0
          if(fireHydrantMarkers.length !== 0 ){
            fireHydrantMarkers.forEach((fireHydrantMarker)=>{
              if(item.id !== fireHydrantMarker.itemId ){
                count++
              } 
            })
            if(count === fireHydrantMarkers.length ){
              newMarkers.push(newMarker)
              fireHydrantMarkers.push(newMarker)
              markerId++
              count = 0 
            }
          }else{
            newMarkers.push(newMarker)
            fireHydrantMarkers.push(newMarker)
            markerId++
          }
        }) 
      }
      
      mapCtx.addMarkers({
          markers: newMarkers,
          clear:false
      })
    },

    // 展示当前区域线段标记
    async showLines(currentRegion) {
      const resp = await app.call({
        path:'/line/search',
        method: 'post',
        header: {
          'X-WX-SERVICE': 'fire-assistant-s',
          'tokens': getTokenKey()//必须添加#######
        },
        data : {
          minLatitude : currentRegion.southwest.latitude,
          maxLatitude : currentRegion.northeast.latitude,
          minLongitude: currentRegion.southwest.longitude,
          maxLongitude: currentRegion.northeast.longitude,
          size: 600
        }
      })
      // 标识线段
      resp.content.forEach((item)=>{
        let points = []
        item.points.forEach((every) => {
          let point = {};
          point.latitude = every.latitude;
          point.longitude = every.longitude;
          points.push(point);
        })
        // 线段
        let line = {
          id: item.id,
          points,
          color: "#9d2933",
          width: 4,
        }
        // 线段标记
        const linemarker = {
          id: markerId,
          itemId: item.id,
          iconPath: "../../images/marker.png",
          type: "line",
          width: 18,
          height: 18,
          latitude: item.latitude,
          longitude: item.longitude
        }
        //添加新currentLines 没有的polyline
        let count = 0
        if(currentLines.length !== 0 ){
          currentLines.forEach((currentLine)=>{
            if(item.id !== currentLine.id ){
              count++
            } 
          })
          if(count === currentLines.length ){
            currentLines.push(line)
            lineMarkers.push(linemarker)
            markerId++
            count = 0 
          }
        }else{
          currentLines.push(line)
          lineMarkers.push(linemarker)
          markerId++
        }
      })
      this.setData({polyLines: currentLines})
      mapCtx.addMarkers({markers: lineMarkers})
    },

    // 展示当前区域标记
    async showGons(currentRegion) {
      const resp = await app.call({
        path:'/polygon/search',
        method: 'post',
        header: {
          'X-WX-SERVICE': 'fire-assistant-s',
          'tokens': getTokenKey()//必须添加#######
        },
        data : {
          minLatitude : currentRegion.southwest.latitude,
          maxLatitude : currentRegion.northeast.latitude,
          minLongitude: currentRegion.southwest.longitude,
          maxLongitude: currentRegion.northeast.longitude,
          size: 600
        }
      })
      resp.content.forEach((item)=>{
        let points = []
        item.points.forEach((every) => {
          let point = {};
          point.latitude = every.latitude;
          point.longitude = every.longitude;
          points.push(point);
        })
        points.push([points[0]])
        let polyGon = {
          id: item.id,
          points,
          fillColor:"#f0b566",
          strokeWidth:1,
        }
         // 区域标记
         const gonmarker = {
          id: markerId,
          itemId: item.id,
          iconPath: "../../images/marker.png",
          type: "gon",
          width: 18,
          height: 18,
          latitude: item.latitude,
          longitude: item.longitude
        }
        
        //添加新currentGons 没有的polygon
        let count = 0
        if(currentGons.length !== 0 ){
          currentGons.forEach((currentGon)=>{
            if(item.id !== currentGon.id ){
              count++
            } 
          })
          if(count === currentGons.length ){
            currentGons.push(polyGon)
            gonMarkers.push(gonmarker)
            markerId++
            count = 0 
          }
        }else{
          currentGons.push(polyGon)
          gonMarkers.push(gonmarker)
          markerId++
        }
      })
      this.setData({polyGons: currentGons})
      mapCtx.addMarkers({markers: gonMarkers})
    },

    // 展示当前圆形标记
    async showOthers(currentRegion) {
      const resp = await app.call({
        path:'/circle/search',
        method: 'post',
        header: {
          'X-WX-SERVICE': 'fire-assistant-s',
          'tokens': getTokenKey()//必须添加#######
        },
        data : {
          minLatitude : currentRegion.southwest.latitude,
          maxLatitude : currentRegion.northeast.latitude,
          minLongitude: currentRegion.southwest.longitude,
          maxLongitude: currentRegion.northeast.longitude,
          size: 600
        }
      })
      resp.content.forEach((item)=>{
        let circle = {
          id: item.id,
          latitude: item.latitude,
          longitude: item.longitude,
          radius: item.radius,
          color: "#a5cfd5",
          fillColor: "#a5cfd5",
          strokeWidth: 1,
        }
        // 其它标记
        const otherMarker = {
          id: markerId,
          itemId: item.id,
          iconPath: "../../images/marker.png",
          type: "circle",
          width: 18,
          height: 18,
          latitude: item.latitude,
          longitude: item.longitude
        }
        //添加新others 没有的circle
        let count = 0
        if(others.length !== 0 ){
          others.forEach((other)=>{
            if(item.id !== other.id ){
              count++
            } 
          })
          if(count === others.length ){
            others.push(circle)
            otherMarkers.push(otherMarker)
            markerId++
            count = 0 
          }
        }else{
          others.push(circle)
          otherMarkers.push(otherMarker)
          markerId++
        }
      })
      this.setData({circles: others})
      mapCtx.addMarkers({markers: otherMarkers})
    },

     //更新marker区域
    updateMarkers(){
      this._loadingMarkers(this.data.currentRegion)
    },
    
    //加载目的地标记
    _loadDescMarkers(){
      // 目的地标记点
      descMarker = [];
      const marker= {
        id: 0,
        iconPath: "../../images/destination.png",
        type: "desc",
        width: 36,
        height: 36,
        latitude: parseFloat(this.data.destination.latitude),
        longitude: parseFloat(this.data.destination.longitude)
      } 
      descMarker.push(marker)
      mapCtx.addMarkers({
        markers:descMarker
      })
    },

    //加载消防站位置点
    async _loadStation(){
      var that = this
      wx.getLocation({
        type: "gcj02",
        success:function(res){ 
          var resp = res
          qqmapsdk.reverseGeocoder({
            location:{
              latitude:resp.latitude,
              longitude:resp.longitude
            },
            success: function(res) {
              that.setData({
                "province": res.result.address_component.province,
                "city": res.result.address_component.city
              })
            }
          })
        }
      })
      const res = await app.call({
        path:'/company/search',
        method: 'POST',
        header: {
            'X-WX-SERVICE': 'fire-assistant-s',
            'tokens': getTokenKey()//必须添加#######
          },
        data:{"province":this.data.province,"cityName":this.data.city,"size":600}
      })
      if(res.content){
        res.content.forEach((item) => {
          const stationMarker = {
            id: markerId,
            itemId: item.id,
            type:"station",
            iconPath: "../../images/station.png",
            width: 36,
            height: 36,
            companyName:item.companyName,
            radius:item.radius,
            latitude: parseFloat(item.latitude),
            longitude: parseFloat(item.longitude)
          }
          markerId++
          stationMarkers.push(stationMarker)
          mapCtx.addMarkers({
            markers:stationMarkers
          })
        })
      }
    },

    //切换位置
    moveLocation:function(e){
      mapCtx.moveToLocation()
      this.setData({scale:16})
    },

    //将视图变换为搜索地
    gotoAddress(destination){
      this.setData({
        'destination.latitude' : destination.latitude,
        'destination.longitude' : destination.longitude,
        'destination.title' : destination.title,
        'destination.address' :  destination.addr
      }),
      mapCtx.moveToLocation({
        latitude:destination.latitude,
        longitude:destination.longitude
      }),
      this._loadDescMarkers()
    },

    //添加现有标记点
    addMarkers(markers){
      mapCtx.addMarkers({
        markers: markers
      })
      this.setData({isShowExistMarkers: true})  
    },
    
    //移除现有标记点
    removeMarkers() {
      if(descMarker.length!==0){
        mapCtx.addMarkers({
          clear: true,
          markers: stationMarkers.concat(descMarker)
        })
      }else{
        mapCtx.addMarkers({
          clear: true,
          markers:stationMarkers
        })
      }
      this.setData({
        isShowExistMarkers: false
      })
    },

    addCurrentLines(){
      this.setData({
        polyLines:currentLines
      })
      mapCtx.addMarkers({
        markers: lineMarkers
      })
      this.setData({isShowExistMarkers: true})  
    },
    removePolyLines(){
      this.setData({
        polyLines:[]
      })
      this.setData({isShowExistMarkers: false})
    },
    addCurrentGons(){
      this.setData({
        polyGons:currentGons
      })
      mapCtx.addMarkers({
        markers: gonMarkers
      })
      this.setData({isShowExistMarkers: true})  
    },
    removePolyGons(){
      this.setData({
        polyGons:[]
      })
      this.setData({isShowExistMarkers: false})
    },
    addOthers(){
      this.setData({
        circles: others
      })
      mapCtx.addMarkers({
        markers: otherMarkers
      })
      this.setData({isShowExistMarkers: true})  
    },
    removeOthers(){
      this.setData({
        circles:[]
      })
      this.setData({isShowExistMarkers: false})
    },
    removeAll(){
      this.removePolyLines() 
      this.removeMarkers()
      this.removePolyGons() 
      this.removeOthers()
    },
    onMapTap(){
      this.triggerEvent('mapTap')
    },
    onMarkerTap(e) {
      let markers = null
      let clickMarker = null
      switch(this.data.markerClassId){
        case 0:
          markers = [...stationMarkers,...descMarker]
          clickMarker = markers.filter((item)=>{
            return item.id===e.markerId
          })
          this.triggerEvent('markertap',clickMarker) 
          break; 
        case 1:
          markers = [...stationMarkers, ...descMarker, ...fireHydrantMarkers]
          clickMarker = markers.filter((item)=>{
            return item.id===e.markerId
          })
          this.triggerEvent('markertap',clickMarker) 
          break;
        case 2:
          markers = [...stationMarkers, ...descMarker, ...lineMarkers]
          clickMarker = markers.filter((item)=>{
            return item.id===e.markerId
          })
          this.triggerEvent('markertap',clickMarker) 
          break;
        case 3:
          markers = [...stationMarkers, ...descMarker, ...gonMarkers]
          clickMarker = markers.filter((item)=>{
            return item.id===e.markerId
          })
          this.triggerEvent('markertap',clickMarker) 
          break;
        case 4:
          markers = [...stationMarkers, ...descMarker, ...otherMarkers]
          clickMarker = markers.filter((item)=>{
            return item.id===e.markerId
          })
          this.triggerEvent('markertap',clickMarker) 
          break;
        case 5:
            markers = stationMarkers
            clickMarker = markers.filter((item)=>{
              return item.id===e.markerId
            })
            this.triggerEvent('markertap',clickMarker) 
            break; 
      }    
    },
  },
})
